package com.lw.yygh.msm.controller;

import com.lw.yygh.msm.service.MsmService;
import com.lw.yygh.msm.utils.RandomUtil;
import com.lw.yygh.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
public class MsmApiController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate redisTemplate;

    //发送手机验证码

    @GetMapping("/send/{phone}")
    public Result sendCode(@PathVariable String phone){
        //从redis 获取验证码，如果获取得到，返回ok
        //key 手机号， value验证码
        String code= (String) redisTemplate.opsForValue().get( phone );
        if (!StringUtils.isEmpty( code )){
            return Result.ok();
        }
        //如果从redis获取不到，生成验证码，通过整合短信服务进行发送，生成验证码放置redis中，设置有效时间
        code= RandomUtil.getSixBitRandom();
        boolean isSend = msmService.send(phone,code);//调用service进行实现
        if (isSend){
            redisTemplate.opsForValue().set( phone,code,5, TimeUnit.MINUTES );
            return Result.ok();
        }else {
            return Result.fail().message( "发送短信失败" );
        }
    }
    //提醒就诊
    @GetMapping("/inner/patientTask/{phone}")
    public void patientTask(@PathVariable String phone){
        msmService.send( phone );
    }
}
